package main

import (
	"fmt"
	"image"
	"os"
	"reflect"

	tiff "github.com/chai2010/tiff"
)

func main() {
	fmt.Println("Testing GeoTIFF data type handling")
	
	// Load the TIFF file
	filename := "./demdata/ClipResult.tif"
	file, err := os.Open(filename)
	if err != nil {
		fmt.Printf("Failed to open TIFF file: %v\n", err)
		return
	}
	defer file.Close()

	// Get image config to understand the data type
	cfg, err := tiff.DecodeConfig(file)
	if err != nil {
		fmt.Printf("Failed to decode config: %v\n", err)
		return
	}
	
	fmt.Printf("Image config: %+v\n", cfg)
	fmt.Printf("Color model: %T\n", cfg.ColorModel)
	
	// Reset file pointer
	file.Seek(0, 0)
	
	// Try to decode just a small section to avoid memory issues
	fmt.Println("Attempting to decode image...")
	img, err := tiff.Decode(file)
	if err != nil {
		fmt.Printf("Failed to decode TIFF: %v\n", err)
		return
	}
	
	fmt.Printf("Successfully decoded image\n")
	fmt.Printf("Image bounds: %+v\n", img.Bounds())
	fmt.Printf("Image type: %T\n", img)
	fmt.Printf("Image type reflect: %s\n", reflect.TypeOf(img))
	
	// Check if it's a specific image type
	switch img := img.(type) {
	case *image.Gray16:
		fmt.Println("Image is *image.Gray16 - this is what we want!")
		// Check a pixel value
		x, y := 9361, 5669
		if x >= 0 && y >= 0 && x < img.Bounds().Dx() && y < img.Bounds().Dy() {
			value := img.Gray16At(x, y)
			signedValue := int16(value.Y)
			fmt.Printf("Gray16 value at (%d, %d): %d (as signed: %d)\n", x, y, value.Y, signedValue)
			
			// Check if this is in the expected range
			if signedValue >= 247 && signedValue <= 5993 {
				fmt.Printf("Value is in expected range! This looks correct.\n")
			} else {
				fmt.Printf("Value is outside expected range. May need scaling.\n")
			}
		}
	case *image.Gray:
		fmt.Println("Image is *image.Gray - this is 8-bit, not what we want")
		// Check a pixel value
		x, y := 9361, 5669
		if x >= 0 && y >= 0 && x < img.Bounds().Dx() && y < img.Bounds().Dy() {
			value := img.GrayAt(x, y)
			fmt.Printf("Gray value at (%d, %d): %d\n", x, y, value.Y)
		}
	default:
		fmt.Printf("Image is unknown type: %T\n", img)
		fmt.Println("This may be the problem - we're not getting the right data type")
		
		// Try to get pixel value anyway
		x, y := 9361, 5669
		if x >= 0 && y >= 0 && x < img.Bounds().Dx() && y < img.Bounds().Dy() {
			color := img.At(x, y)
			fmt.Printf("Pixel color at (%d, %d): %+v\n", x, y, color)
			
			// Try to get as RGBA
			r, g, b, a := color.RGBA()
			fmt.Printf("RGBA values: R=%d, G=%d, B=%d, A=%d\n", r, g, b, a)
			
			// Try to reconstruct the original value
			// For 16-bit data mapped to RGBA, we might need to use only one channel
			fmt.Printf("R value as 16-bit: %d\n", r)
			fmt.Printf("G value as 16-bit: %d\n", g)
			fmt.Printf("B value as 16-bit: %d\n", b)
		}
	}
}
